
var path = require("path");
var moment = require('moment-timezone');
moment.tz.setDefault('Asia/Shanghai');
var fs = require("fs");
var http = require("http");
var log4js = require("log4js");

global.PORT = process.env.PORT || 80;

/** log4js initiation */
if (!fs.existsSync(path.join(__dirname, "logs"))) {
    fs.mkdirSync(path.join(__dirname, "logs"));
}

log4js.configure({
    appenders: {
        out: { type: 'console' }
    },
    categories: {
        default: { appenders: ['out'], level: 'info' }
    }
});

var logger = log4js.getLogger("app");

/** express */
var express = require("express");
var favicon = require('serve-favicon');

var app = express();

var server = require('http').Server(app);

app.use(
    log4js.connectLogger(log4js.getLogger("http"), {
        level: "auto",
        nolog: ["\\.css", "\\.js", "\\.html", "\\.map", "\\.png", "\\.jpg", "\\.woff"]
    })
);
app.use(favicon(__dirname + '/dist/favicon.ico'));

app.use(express.text({ type: '*/xml' }));
app.use((req, res, next)=>{
    if(req.headers['content-encoding'] && req.headers['content-encoding'].toLowerCase().startsWith('utf')){
        delete req.headers['content-encoding'];
    }
    express.json({ limit: "50mb"})(req, res, next);
});
app.use(express.urlencoded({ limit: "50mb", extended: true }));


app.set('trust proxy', true);

app.use(express.static(path.join(__dirname, "dist")));
app.use("/static", express.static(path.join(__dirname, "dist", "static")));
app.use("/node_modules", express.static(path.join(__dirname, "node_modules")));

// error handlers
app.use(function (err, req, res, next) {
    if (err.name === "UnauthorizedError") {
        res.sendStatus(401);
        return;
    }
    console.log(err);
    res.status(500).send(err.message);
});

app.all("*", function (req, res, next) {
    res.header("Access-Control-Allow-Origin", req.headers.origin || "*");
    res.header(
        "Access-Control-Allow-Headers",
        "Content-Type,Content-Length, Authorization,'Origin',Accept,X-Requested-With"
    );
    res.header(
        "Access-Control-Allow-Methods",
        "GET, POST, OPTIONS, PUT, PATCH, DELETE"
    );
    res.header("Access-Control-Allow-Credentials", true);
    if (req.method === "OPTIONS") {
        res.sendStatus(200);
    } else {
        next();
    }
});

require("./server/router")(app);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    res.status(404).send(`${req.path} 页面找不到`);
    logger.warn(`${req.path} 页面找不到`);
});

server.listen(global.PORT, function () {
    logger.info("app 启动监听" + server.address().port);
});
